<?php
/**
 * created by zzy
 * date: 2017/10/24 9:28
 */


namespace App\Http\Admin\Company\Controllers;
use App\Engine\Func;
use App\Http\Admin\Company\Models\Company;
use Framework\BaseClass\Http\Admin\Controller;
use App\Eloquent\Ygt\DepartmentUser;
use App\Eloquent\Ygt\User;
use App\Http\Admin\Company\Models\Department;
use App\Http\Admin\Company\Models\Privilege;
class DepartmentController extends Controller
{
    public function index()
    {
    }
    public function lists()
    {
        $adminUser         = request()->user('admin')->toArray();
        $companyId         = $adminUser['company_id'];
        if (request()->isMethod('post')) {

            $pageSize       = request('pageSize', 30);
            $pageCurrent    = request('pageCurrent', 1);
            $offset         = ($pageCurrent - 1) * $pageSize;

            $where          = ['company_id'=>$companyId];
            $lists          = Department::getList( $where,'',$pageSize,$offset )->toArray();
            $count          = Department::getCount($where);
            $data           = ['totalRow'=>$count,'pageCurrent'=>$pageCurrent,'list'=>$lists];
            $data_json      = json_encode($data);
            return $data_json;
        } else {
            $company_json   = Company::getJsonList();
            return $this->view('lists', compact('company_json'));
        }
    }

    public function edit()
    {
        $adminUser         = request()->user('admin')->toArray();
        $companyId         = $adminUser['company_id'];

        $params             = $this->requestJson();
        $id                 = isset($params['id']) ? $params['id'] : 0;
        $pid                = isset($params['pid']) ? $params['pid'] : 0;
        $title              = $params['title'];
        $data               = ['pid'=>$pid,'title'=>$title];

        if( $id ){
            $where          = ['id'=>$id];
            $result         = Department::updateOneData( $where, $data );
        } else {
            $data['company_id']     = $companyId;
            $result                   = Department::insertOneData( $data, 'id' );
        }
        if( $result ){
            return $this->ajaxSuccess( '成功' );
        } else {
            return $this->ajaxFail( '失败' );
        }
    }
    public function delete()
    {
        $adminUser         = request()->user('admin')->toArray();
        $companyId         = $adminUser['company_id'];

        $params             = $this->requestJson();
        $id                 = isset($params['id']) ? $params['id'] : 0;
        if( $id ){
            $where          = ['company_id'=>$companyId,'id'=>$id];
            $info           = Department::getInfo(['id'=>$id]);
            $del_result     = Department::del($where);
            if( $del_result !== false ){
                if( $info ){
                    $pid        = $info->id;
                    if( $pid != 0 ){
                        $where      = ['company_id'=>$companyId,'pid'=>$pid];
                        $del_result = Department::del($where);
                    }
                }
                if( $del_result !== false ){
                    return $this->ajaxSuccess('成功');
                } else {
                    return $this->ajaxFail('失败1');
                }
            }
            return $this->ajaxFail('失败2');
        } else {
            return $this->ajaxFail('失败3');
        }
    }

    public function userLists(){

        $adminUser          = request()->user('admin')->toArray();
        $companyId          = $adminUser['company_id'];
        if (request()->isMethod('post')) {

            $truename           = request('truename','');
            $mobile             = request('mobile','');
            $departmentId       = request('department_id','');
            $privilegeId        = request('privilege_id','');
            $where              = ['company_id'=>$companyId];
            if( $truename )
            {
                $truename                = '%'.$truename.'%';
                $where['truename']      = ['like',$truename];
            }
            if( $mobile )
            {
                $mobile                = '%'.$mobile.'%';
                $where['mobile']      = ['like',$mobile];
            }
            if( $departmentId )
            {
                $where['department_id']     = $departmentId;
            }
            if( $privilegeId )
            {
                $where['privilege_id']      = $privilegeId;
            }
            $fields             = '';
            $limit              = '';
            $offset             = '';
            $orderby            = ['department_id','asc'];
            $collection         = DepartmentUser::getList( $where,$fields,$limit,$offset,$orderby );
            $result             = $collection->toJson();
            return $result;
        } else {
            $where              = ['company_id'=>$companyId];
            $departmentList     = Department::getList($where)->toArray();
            $departmentJson     = Func::getIdTitleByType($departmentList,4);
            $privilegeList      = Privilege::getList($where);
            $privilegeJson      = Func::getIdTitleByType($privilegeList,4);
            $data               = [
                'department_list'=>$departmentList,'privilege_list'=>$privilegeList,
            ];
            $jsonData           = [
                'department_list'=>$departmentJson,'privilege_list'=>$privilegeJson,
            ];
            return $this->view('user-lists',compact('data','jsonData') );
        }
    }
    public function userEdit()
    {
        $adminUser          = request()->user('admin')->toArray();
        $companyId          = $adminUser['company_id'];

        $params             = $this->requestJson();
        $id                 = isset($params['id']) ? $params['id'] : 0;
        $truename           = $params['truename'];
        $mobile             = $params['mobile'];
        $price              = isset($params['price']) ? floatval($params['price']) : 0.00000;
        $departmentId       = isset($params['department_id']) ? $params['department_id'] : 0;
        $privilegeId        = $params['privilege_id'];
        $isLeader           = $params['is_leader'];

        //手机号码不存在则默认注册
        $where              = ['mobile'=>$mobile];
        $user               = User::getInfo( $where );
        if( !$user ){
            //return $this->ajaxFail( '未注册' );
            $passwordMd5    = User::passwordMd5( '123456', '123123' );
            $userData       = [
                'mobile'=>$mobile, 'truename'=>$truename,'company_id'=>$companyId,
                'password'=>$passwordMd5, 'salt'=>'123123'
            ];
            $userId         = User::insertOneData( $userData, 'id' );
            $userTruename   = $truename;
        } else {
            $userId         = $user->id;
            $userTruename   = $user->truename;
            $userCompanyId  = $user->company_id;
            $saleArr        = config('ygt.sale_arr');
            $sellerArr      = config('ygt.seller_arr');
            $companyIdArr   = [
                $saleArr['company_id'],$sellerArr['company_id'],
            ];
            if(in_array($userCompanyId,$companyIdArr))
            {
                return $this->ajaxFail( '该手机号已注册为其它角色' );
            }
        }

        $departmentUserData = [
            'truename'=>$truename, 'department_id'=>$departmentId,
            'privilege_id'=>$privilegeId, 'is_leader'=>$isLeader,
            'price'=>$price
        ];
        //更新或者添加
        if( $id ){
            $where          = ['company_id'=>$companyId,'mobile'=>$mobile];
            $departmentUser = DepartmentUser::getInfo( $where );
            if( $departmentUser && $id != $departmentUser->id  ){
                return $this->ajaxFail( '已存在' );
            }
            $where          = ['company_id'=>$companyId,'id'=>$id];
            $result         = DepartmentUser::updateOneData( $where, $departmentUserData );
            if($userTruename != $truename)
            {
                $truenameData       = ['truename'=>$truename];
                User::updateOneData( ['id'=>$userId], $truenameData );
                DepartmentUser::where('user_id',$userId)->update($truenameData);
            }
        } else {
            $where          = ['company_id'=>$companyId,'mobile'=>$mobile];
            $departmentUser = DepartmentUser::getInfo( $where );
            if( $departmentUser ){
                return $this->ajaxFail( '已存在' );
            }
            User::updateOneData( ['id'=>$userId], ['company_id'=>$companyId] );
            $departmentUserData['mobile']       = $mobile;
            $departmentUserData['user_id']      = $userId;
            $departmentUserData['company_id']   = $companyId;
            $result         = DepartmentUser::insertOneData($departmentUserData);
        }
        if( $result ){
            return $this->ajaxSuccess( '成功' );
        } else {
            return $this->ajaxFail( '失败' );
        }
    }
    public function userDelete()
    {
        $adminUser         = request()->user('admin')->toArray();
        $companyId         = $adminUser['company_id'];

        $id                 = request( 'id', 0 );
        if( $id ){
            $idArrTemp      = explode(',', $id);
            $idArr          = [];
            foreach( $idArrTemp as $key=>$val ){
                $idArr[]    = intval($val);
            }
            $where              = ['company_id'=>$companyId,'id'=>['in',$idArr]];
            $departUserList     = DepartmentUser::getList( $where );
            $userIdArr          = [];
            foreach( $departUserList as $key=>$val ){
                $userIdArr[]  = $val->user_id;
            }
            $delResult          = DepartmentUser::del($where);
            if( $delResult !== false ){
                foreach( $userIdArr as $key=>$val ){
                    $where      = ['user_id'=>$val];
                    $dUser      = DepartmentUser::getInfo($where);
                    $userCompanyId          = 0;
                    if($dUser)
                    {
                        $userCompanyId      = $dUser->company_id;
                    }
                    User::updateOneData( ['id'=>$val], ['company_id'=>$userCompanyId] );
                }
                return $this->ajaxSuccess('成功');
            } else {
                return $this->ajaxFail('失败1');
            }
        } else {
            return $this->ajaxFail('失败2');
        }
    }
    public function userPrivilege()
    {
        $adminUser         = request()->user('admin')->toArray();
        $companyId         = $adminUser['company_id'];

        $id                     = request('id');
        if(request()->isMethod('post')){
            $privilegeId       = request('privilege_id');
            $where              = ['id'=>$id];
            $data               = ['privilege_id'=>$privilegeId];
            $result             = DepartmentUser::updateOneData( $where, $data );
            if( $result ){
                return $this->ajaxSuccess( '成功' );
            } else {
                return $this->ajaxFail( '失败' );
            }
        } else {
            $where              = ['id' => $id];
            $info               = DepartmentUser::getInfo($where);
            $department_list    = Department::getList(['company_id'=>$companyId], 'id,title');
            $privilege_list     = Privilege::getList(['company_id'=>$companyId], 'id,title');

            return $this->view('user-privilege', compact('info', 'department_list', 'privilege_list'));
        }
    }
}